﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SvnCrowdConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            var inputFolder = new DirectoryInfo(args[0]);

            var svnLocationFactory = new SvnLocationFactory(new WorkingDirIoAdapter(inputFolder.FullName));
            var locations = inputFolder.GetFiles("*.conf", SearchOption.TopDirectoryOnly);
            var svnAuths = locations.Select(l => (ISvnLocation)svnLocationFactory.Create(File.ReadAllText(l.FullName)));

            using (var fileStream = File.Open(Path.Combine(inputFolder.FullName, "dav_svn.authz"), FileMode.Create, FileAccess.Write))
            using (var writer = new StreamWriter(fileStream))
            {
                writer.Write(ConvertToAuthz(svnAuths));
            }
        }

        public static string ConvertToAuthz(IEnumerable<ISvnLocation> svnLocations)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine();
            stringBuilder.AppendLine(@"[groups]");

            var svnLocationsList = svnLocations.ToList();

            AddGroups(svnLocationsList.SelectMany(x => x.Groups).Distinct(), stringBuilder);

            stringBuilder.AppendLine();

            foreach (var svnLocation in svnLocationsList)
            {
                stringBuilder.AppendLine(String.Format("[{0}:/]", svnLocation.Repo));
                svnLocation.Groups.ToList().ForEach(g => stringBuilder.AppendLine(String.Format("@{0} = rw", g)));
                stringBuilder.AppendLine();
            }

            return stringBuilder.ToString();
        }

        private static void AddGroups(IEnumerable<string> groups, StringBuilder stringBuilder)
        {
            foreach (var @group in groups)
            {
                stringBuilder.AppendLine(string.Format("{0} =", @group));
            }
        }
    }
}
